package com.linwen.javase.thread;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : linwen
 * @date : 上午12:42 2021/1/12
 */
public class 线程锁5 {
    public static void main(String[] args) {
        Window5 window5 = new Window5();
        Thread thread1 = new Thread(window5);
        Thread thread2 = new Thread(window5);
        Thread thread3 = new Thread(window5);
        thread1.setName("窗口1");
        thread2.setName("窗口2");
        thread3.setName("窗口3");
        thread1.start();
        thread2.start();
        thread3.start();
    }
}
class Window5 implements Runnable{
    private int ticket = 100;
    //参数 fair  是否是公平的，线程依次执行
    private ReentrantLock lock = new ReentrantLock(true);
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //lock()要放在try代码块中
            //在finally中解锁
            try{
                lock.lock();
                if(ticket>0){
                    System.out.println(Thread.currentThread().getName()+"="+ticket);
                    ticket--;
                }else {
                    break;
                }
            }finally {
                lock.unlock();
            }

        }
    }
}
